/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.tom.social.watcher.agent.behaviour;

import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import pl.tom.social.common.types.ConversationIDType;
import pl.tom.social.watcher.jade.LocalJade;

/**
 *
 * @author Tom
 */
public class AdminBehaviour extends CyclicBehaviour {

	private static final Logger logger = Logger.getLogger(AdminBehaviour.class);

	@Override
	public void action() {
		int nr;

		//Wait for message from outer agent.
		ACLMessage msg = myAgent.blockingReceive();
		if (msg != null) {
			String cId = msg.getConversationId();
			if (cId != null && cId.length() > 0) {
				ConversationIDType type = ConversationIDType.valueOf(cId);
				switch (type) {
					case AddSearcher:
						LocalJade.getInstance().newAgent(msg.getSender(), msg.getContent());
						acceptProposal(msg);
						break;
					case CancelSearcher:
						try {
							nr = Integer.parseInt(msg.getContent());
							LocalJade.getInstance().cancelAgent(nr);
						} catch (Exception ex) {
							logger.log(Level.ERROR, null, ex);
						}
						break;
					case AddUpdater:
						LocalJade.getInstance().newAgent(msg.getSender(), null);
						break;
					case CancelUpdater:
						try {
							nr = Integer.parseInt(msg.getContent());
							LocalJade.getInstance().cancelAgent(nr);
						} catch (Exception ex) {
							logger.log(Level.ERROR, null, ex);
						}
						break;
				}
			}
		}
	}

	private void acceptProposal(ACLMessage msg) {
		ACLMessage reply = msg.createReply();
		reply.setPerformative(ACLMessage.ACCEPT_PROPOSAL);
		myAgent.send(reply);
	}
}
